<template>
  <div>
    <div class="list-table mb20">
      <div class="area-header" style="display: flex;align-items: center;">
        <span class="area-header-title">{{ $t('指标统计') }}</span>
        <el-switch
          v-model="isLp"
          :inactive-text="$t('仅查看LP')"
          @change="switchChange"
        />
      </div>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-table
            v-loading="indicatorsLoading"
            :data="chartList.data"
            :max-height="226"
            :cell-style="tableStyle"
            border
          >
            <el-table-column
              v-for="(col, index) in chartList.columns"
              :key="index"
              :label="col.label"
              align="center"
              show-overflow-tooltip
              :prop="col.prop"
              :min-width="col.prop === 'type' ? 100 : 120"
              :fixed="col.prop === 'type' ? 'left' : false"
            >
              <template slot="header">
                <span>{{ col.label }}</span>
              </template>
              <template slot-scope="scope">
                <span v-if="scope.row.type === 'fundGrossIrr' || scope.row.type === 'fundNetIrr' || scope.row.type === 'fundLpNetIrr'">
                  <span v-if="col.prop === 'type'">{{ selectDictLabel(indicatorsOptions,scope.row[col.prop]) }}</span>
                  <span v-else class="money-text"><el-link type="primary" @click="findXIrrDetails(scope.row[col.prop].id)">{{ scope.row[col.prop] ? moneyFormat(scope.row[col.prop].xirr,'rate') : '' }}</el-link></span>
                </span>
                <span v-else>
                  <span v-if="col.prop === 'type'">
                    <span v-if="scope.row[col.prop] === 'fundDpi' || scope.row[col.prop] === 'fundLpDpi'">
                      {{ selectDictLabel(indicatorsOptions,scope.row[col.prop]) }}
                      <el-tooltip :content="$t('出资人分配金额 / 出资人实缴金额')" placement="top">
                        <i class="el-icon-question" />
                      </el-tooltip>
                    </span>
                    <span v-else-if="scope.row[col.prop] === 'fundMoic'">
                      {{ selectDictLabel(indicatorsOptions,scope.row[col.prop]) }}
                      <el-tooltip :content="$t('(投资回款+投资组合估值) / 项目付款')" placement="top">
                        <i class="el-icon-question" />
                      </el-tooltip>
                    </span>
                    <span v-else-if="scope.row[col.prop] === 'fundTvpi' || scope.row[col.prop] === 'fundLpTvpi'">
                      {{ selectDictLabel(indicatorsOptions,scope.row[col.prop]) }}
                      <el-tooltip :content="$t('(基金分配总额＋基金最新估值) / 出资人实缴金额')" placement="top">
                        <i class="el-icon-question" />
                      </el-tooltip>
                    </span>
                    <span v-else-if="scope.row[col.prop] === 'fundRvpi' || scope.row[col.prop] === 'fundLpRvpi'">
                      {{ selectDictLabel(indicatorsOptions,scope.row[col.prop]) }}
                      <el-tooltip :content="$t('TVPI - DPI')" placement="top">
                        <i class="el-icon-question" />
                      </el-tooltip>
                    </span>
                    <span v-else>
                      {{ selectDictLabel(indicatorsOptions,scope.row[col.prop]) }}
                    </span>
                  </span>
                  <span v-else class="money-text">{{ scope.row[col.prop] ? moneyFormat(scope.row[col.prop].xirr,'rate') : '' }}</span>
                </span>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
        <el-col :span="12">
          <el-table
            v-loading="typeLoading"
            :data="dataChartList.data"
            :cell-style="tableStyle1"
            :max-height="226"
            border
          >
            <el-table-column
              v-for="(col, index) in dataChartList.columns"
              :key="index"
              :label="col.label"
              align="center"
              show-overflow-tooltip
              :prop="col.prop"
              :min-width="col.prop === 'type' ? 100 : 120"
              :fixed="col.prop === 'type' ? 'left' : false"
            >
              <template slot-scope="scope">
                <span v-if="col.prop === 'type'">{{ scope.row[col.prop] === '合计' ? scope.row[col.prop] : selectDictLabel(operteTypeOptions,scope.row[col.prop]) }}</span>
                <span v-else class="money-text">{{ moneyFormat(scope.row[col.prop]) }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </div>
    <div v-loading="tableLoading" class="list-table mb20">
      <el-row id="table" class="table" :gutter="10">
        <el-col v-for="(statistical,index) in dataList" :key="index" :span="6">
          <div v-for="(value,key) in statistical" :key="key" class="fund-parent mb10">
            <div class="left-text">
              <circle-chart :expense="[expenseSum, value]" style="width: 2vh;display: inline-block;" />
              <el-tooltip class="item" effect="dark" :content="selectDictLabel(operteTypeOptions,key)" placement="bottom">
                <div class="label">{{ key === 'SUM' ? '合计' : selectDictLabel(operteTypeOptions,key) }}</div>
              </el-tooltip>
            </div>
            <div class="money" style="color: #333436;font-weight: bold;">{{ moneyFormat(value) }}</div>
          </div>
        </el-col>
      </el-row>
    </div>
    <div class="list-table noPad">
      <el-tabs v-model="activeName" @tab-click="clickMenu">
        <el-tab-pane v-for="(item, key) in childMenuTabs" :key="key" :lazy="true" :label="$t(item.menuName)" :name="item.menuName">
          <component :is="menuPath" v-show="item.flag" ref="menuPath" />
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 添加或修改xIrr计算明细对话框 -->
    <el-dialog :title="$t('计算明细')" :visible.sync="xIrrOpen" :close-on-click-modal="false" :lock-scroll="false" :width="'50%'" custom-class="customDialog" append-to-body>
      <xIrrBaseDetailsList ref="xIrrBaseDetailsList" />
      <div slot="footer" class="dialog-footer mt-15" style="text-align: right;">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="exportXIrrHandle"
        >{{ $t('导出') }}
        </el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>

import { childMenuList } from '@/api/system/menu'
import { getAsyncComponent } from '@/utils'
import { getFundBaseFundByFundId } from '@/api/fund/fundBase'
import CircleChart from '@/views/chart/circleChart'
import { getChart, getDicts } from '@/api/fund/cashflow/fundCashflow'
import xIrrBaseDetailsList from '@/components/Xirr/details/xirrBaseDetailsList'
export default {
  components: { CircleChart, xIrrBaseDetailsList },
  data() {
    return {
      // 遮罩层
      loading: false,
      xIrrOpen: false,
      isLp: false,
      activeName: '',
      // 子页签
      childMenuTabs: [],
      // 组件地址
      menuPath: '',
      expenseSum: 0,
      // eslint-disable-next-line no-unused-vars
      tableStyle({ row, column, rowIndex, columnIndex }) {
        if (columnIndex === 0) {
          return {
            background: 'rgba(246, 247, 251, 1)'
          }
        }
      },
      // eslint-disable-next-line no-unused-vars
      tableStyle1({ row, column, rowIndex, columnIndex }) {
        if (column.property.indexOf('FY-') !== -1 || columnIndex === 0) {
          return {
            background: 'rgba(246, 247, 251, 1)'
          }
        }
      },
      chartList: {},
      dataChartList: {},
      dataList: [],
      menuKeyIdent: 'cash_flow_aggregation',
      menuKeyIdentArr: ['cash_flow_aggregation_CB', 'cash_flow_aggregation_QS', 'cash_flow_aggregation_TZ', 'cash_flow_aggregation_SPV'],
      indicatorsOptions: [],
      operteTypeOptions: [],
      typeLoading: true,
      indicatorsLoading: true,
      tableLoading: true
    }
  },
  created() {
    getDicts('zb', { isLp: false }).then(res => {
      this.indicatorsOptions = res.data
      this.getChartList('zb')
    })
    getDicts('type', {}).then(res => {
      this.operteTypeOptions = res.data
      this.getChartList('type')
      this.getLists()
    })
    this.init()
  },
  mounted() {},
  methods: {
    getChartList(type) {
      if (type === 'zb') {
        this.getChartByIndicators()
      } else if (type === 'type') {
        this.getChartByOperateType()
      }
    },
    getChartByIndicators() {
      this.indicatorsLoading = true
      getChart('zb', { busId: this.$route.query.id, isLp: this.isLp }).then(res => {
        this.chartList = { columns: [], data: [] }
        this.chartList = res.data
        console.log(this.chartList.data)
        this.indicatorsLoading = false
      })
    },
    getChartByOperateType() {
      this.typeLoading = true
      getChart('type', { busId: this.$route.query.id }).then(res => {
        console.log(res.data, '现金流类型数据')
        this.dataChartList = { columns: [], data: [] }
        this.dataChartList = res.data
        this.typeLoading = false
      })
    },
    switchChange(e) {
      getDicts('zb', { isLp: e }).then(res => {
        this.indicatorsOptions = res.data
        this.getChartList('zb')
      })
    },
    getLists() {
      this.tableLoading = true
      getChart('sum', { busId: this.$route.query.id }).then(res => {
        var arr = []
        var hasArr = []
        // var sum = 0
        res.data.data.forEach(item => {
          var obj = {}
          obj[item.operateType] = item.operateAmount
          arr.push(obj)
          hasArr.push(item.operateType)
          // sum += item.operateAmount
        })
        this.operteTypeOptions.forEach(dict => {
          if (!hasArr.includes(dict.dictValue)) {
            var obj = {}
            obj[dict.dictValue] = ''
            arr.push(obj)
          }
        })
        // arr.push({ 'SUM': sum })
        // this.expenseSum = sum
        var idx = this.getIndex(arr, 'JJGZ')
        if (idx !== -1) {
          var delIdx = this.getIndex(arr, 'JJGZLP')
          arr.splice(idx + 1, 0, arr[delIdx])
          idx = -1
          if (delIdx !== -1) {
              arr.splice(delIdx + 1, 1)
          }
        }
        idx = this.getIndex(arr, 'JJJK')
        if (idx !== -1) {
          delIdx = this.getIndex(arr, 'JJJKJLP')
          arr.splice(idx + 1, 0, arr[delIdx])
          idx = -1
          if (delIdx !== -1) {
            arr.splice(delIdx + 1, 1)
          }
        }
        this.dataList = arr
        console.log(this.dataList)
        this.tableLoading = false
      })
    },
    getIndex(arr, type) {
      var idx = -1
      arr.forEach((item, index) => {
        var keys = Object.keys(item)
        var key = keys[0]
        if (key === type) {
          idx = index
        }
      })
      return idx
    },
    init() {
      this.loading = true
      getFundBaseFundByFundId(this.$route.query.id).then(response => {
        console.log(response)
        if (response.data !== null && response.data.fundStatus) {
          this.menuKeyIdent += ('_' + response.data.fundStatus)
        }
        if (!this.menuKeyIdentArr.includes(this.menuKeyIdent)) {
          this.menuKeyIdent = 'cash_flow_aggregation_SPV'
        }
        this.listLoad()
      })
    },
    listLoad() {
      this.loading = true
      // 菜单列表
      childMenuList(this.menuKeyIdent).then(response => {
        this.childMenuTabs = response.rows
        if (this.childMenuTabs !== null && this.childMenuTabs !== undefined && this.childMenuTabs.length > 0) {
          this.activeName = this.childMenuTabs[0] === undefined ? '' : this.childMenuTabs[0].menuName
          this.clickMenu(response.rows[0])
        }
        this.loading = false
      })
    },
    clickMenu(tab) {
      this.childMenuTabs && this.childMenuTabs.forEach(item => {
        if (item.menuName === tab.menuName || item.menuName === tab.name) {
          this.$nextTick(() => {
            this.$set(item, 'flag', true)
            this.importFormPath(item.component)
          })
        } else {
          this.$set(item, 'flag', false)
        }
      })
    },
    // 引入组件
    importFormPath(menuPath) {
      if (menuPath) {
        if (menuPath.indexOf('?') === -1) { // 不含问号
          this.menuPath = getAsyncComponent('@/views/' + menuPath)
          this.parameter = {}
        } else {
          const index = menuPath.lastIndexOf('?')
          const sMenuPath = menuPath.substring(0, index)
          this.menuPath = getAsyncComponent('@/views/' + sMenuPath)

          // 增加参数
          const newKey = menuPath.split('?')[1]
          var newstr = newKey.replace(/=/g, '":"')
          const objectKey = '{"' + newstr.replace(/&/g, '","') + '"}'
          this.parameter = JSON.parse(objectKey)
          if (this.parameter !== undefined && this.parameter.dealType !== undefined) {
            this.dealType = this.parameter.dealType
          }
        }
        // 地址栏添加左侧菜单地址
        // this.$nextTick(() => {
        //   this.$route.params.dealType = this.dealType
        // })
      } else {
        const error = 'error/404'
        this.importFormPath(error)
      }
    },
    findXIrrDetails(xIrrId) {
      console.log(xIrrId)
      this.xIrrOpen = true
      this.$nextTick(() => {
        this.$refs.xIrrBaseDetailsList.init(xIrrId)
      })
    },
    exportXIrrHandle() {
      this.$nextTick(() => {
        this.$refs.xIrrBaseDetailsList.exportHandle()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.table {
  .fund-parent {
    background-color: #F8F9FA;
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    overflow: hidden;
    padding: 10px 10px 10px 5px;
  }
  .left-text{
    display: flex;
    align-items: center;
    flex: 1;
    overflow: hidden;
    min-width: 30%;
    .label{
      font-size: 13px;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
    }
  }
  .money{
    font-size: 13px;
  }
  .wrap-pop-expense {
    /* 背景色 */
    background: rgba(0,0,0,.7) !important;
    color: #fff !important;
    border: 1px solid rgba(0,0,0,.7) !important;
  }

  /* 下方是去除三角箭头的代码 */
  .wrap-pop-expense[x-placement^="bottom"] .popper__arrow::after {
    border-bottom-color: rgba(0,0,0,.7) !important;
  }

  .wrap-pop-expense[x-placement^="bottom"] .popper__arrow {
    border-bottom-color: rgba(0,0,0,.7) !important;
  }
}

/deep/.customDialog .el-dialog__body {
  height: 48vh;
  overflow-y: auto;
  .list-table {
    margin: -20px;
  }
}

</style>
